package be.ipl.ieco.servlets;

import ieco.domaine.Etudiant;
import ieco.domaine.Option;
import ieco.domaine.Optionnel;
import ieco.ucc.GestionDEtudiants;
import ieco.ucc.GestionDesChoix;
import ieco.ucc.GestionDesInscriptions;
import ieco.ucc.GestionDesOptionnels;
import ieco.ucc.GestionDesOptions;
import ieco.ucc.GestionDesSeries;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.ieco.dtos.EtudiantDTO;
import be.ipl.ieco.util.Util;

import com.google.gson.GsonBuilder;

@SuppressWarnings("serial")
@WebServlet("/api.html")
public class AjaxHandlerJSONServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	@EJB
	private GestionDEtudiants gestionEtudiants;

	@EJB
	private GestionDesOptions gestionOptions;

	@EJB
	private GestionDesOptionnels gestionOptionnels;

	@EJB
	private GestionDesChoix gestionChoix;

	@EJB
	private GestionDesInscriptions gestionInscription;

	@EJB
	private GestionDesSeries gestionSeries;
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String operation = request.getParameter("operation");
		if (Util.checkString(operation)) {
			HttpSession session = request.getSession();
			synchronized (session) {
				Integer level = (Integer) session.getAttribute("level");
				switch (operation) {
				case "getChoix":
					traitementGetChoix(request, response, level);
					break;
				case "login":
					traitementLogin(request, response);
					break;
				case "getPasswordByMail":
					traitementgetPasswordByMail(request, response);
					break;
				case "persistChoix":
					traitementPersistChoix(request, response, level);
					break;
				case "getDatesAndBorneOpt":
					traitementGetDatesAndBorneOpt(request, response, level);
					break;
				case "persistDates":
					traitementPersistDates(request, response, level);
					break;
				case "persistBorneOpt":
					traitementPersistBorneOpt(request, response, level);
					break;
				case "sendMailToAll":
					traitementSendMailToAll(request, response, level);
					break;
				case "getOptionsAndOptionnels":
					traitementGetOptionsAndOptionnels(request, response, level);
					break;
				case "deleteOptionsOptionnels":
					traitementDeleteOptionsOptionnels(request, response, level);
					break;
				case "persistNewOption":
					traitementPersistNewOption(request, response, level);
					break;
				case "persistNewOptionnel":
					traitementPersistNewOptionnel(request, response, level);
					break;
				case "updateOptionsOptionnels":
					traitementUpdateOptionsOptionnels(request, response, level);
					break;
				case "getAllEtudiantAvecOptionsGagnantes":
					traitementGetAllEtudiantAvecOptionsGagnantes(request,
							response, level);
					break;
				case "getAllEtudiantPourLOption":
					traitementGetAllEtudiantPourLOption(request, response,
							level);
					break;
				case "getAllOptions":
					traitementGetAllOptions(request, response, level);
					break;
				case "getAllEtudiantMalheureux":
					traitementGetAllEtudiantMalheureux(request, response, level);
					break;
				case "getIntersectionsImpossibles":
					traitementGetIntersectionsImpossibles(request, response,
							level);
					break;
				case "enregistrerIntersections":
					traitementEnregistrerIntersections(request, response, level);
					break;
				case "exporterEtudiants":
					traitementExporterEtudiants(request, response, level);
					break;
				case "numeroterEtudiants":
					traitementNumeroterEtudiants(request, response, level);
					break;
				case "getAllEtudiantsParAnnee":
					traitementGetAllEtudiantsParAnnee(request, response, level);
					break;
				case "getAllEtudiants":
					traitementGetAllEtudiants(request, response, level);
					break;
				case "updateEtudiants":
					traitementUpdateEtudiants(request, response, level);
					break;
				case "getAllAnnees":
					traitementGetAllAnnees(request, response, level);
					break;
				case "persistDelibe":
					traitementPersistDelibe(request, response, level);
					break;
				case "persistProEco":
					traitementPersistProEco(request, response, level);
					break;
				case "creerSeries":
					traitementCreerSeries(request, response, level);
					break;
					
				default:
					request.getServletContext()
							.getNamedDispatcher("ErreurParam")
							.forward(request, response);
					break;
				}
			}
		}
	}

	private void traitementCreerSeries(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String listSeries = request.getParameter("listSeries");
				
				if (Util.checkObject(listSeries)) {
					boolean responseCode = true;

					if (Util.checkString(listSeries)) {
						String[] series = listSeries.split(",");
						Map<String,List<Integer>> mapSerieEtudiantMatricule = new HashMap<String,List<Integer>>();
						
						String patternMatricule = "[0-9]+";
						List<Integer> matriculesSerie;
						String serieCourante = null;
						int matricule = 0;
						for (int i = 0; i < series.length; i++) {
							if(!series[i].matches(patternMatricule)){
								serieCourante = series[i];
								matriculesSerie = new ArrayList<Integer>();
								mapSerieEtudiantMatricule.put(serieCourante,matriculesSerie);
							}else{
								matricule = Integer.parseInt(series[i]);
								mapSerieEtudiantMatricule.get(serieCourante).add(matricule);
							}
						}
						
						responseCode = gestionSeries.enregistrerLesSeries(mapSerieEtudiantMatricule);
					}
					
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementPersistProEco(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputEtudiants = request.getParameter("inputEtudiants");
				
				if (Util.checkObject(inputEtudiants)) {
					boolean responseCode = true;

					if (Util.checkString(inputEtudiants)) {
						inputEtudiants = new String(inputEtudiants.getBytes(),"UTF-8");
						
						String[] etudiants = inputEtudiants.split(",");
						List<Etudiant> etudiantsEJB = new ArrayList<Etudiant>();
						
						Etudiant etudiant = null;
						int matricule = 0;
						String email = null, grade = null; 
						double janvier = 0, juin = 0, septembre = 0;
						
						switch (etudiants[0]) {
						case "updateJuin":
							for(int i=1; i<etudiants.length; i=i+2){
								matricule = Integer.parseInt(etudiants[i]);
								etudiant = gestionEtudiants.getEtudiantViaMatricule(matricule);
								if(!etudiants[i+1].isEmpty())
									etudiant.setJuin(Double.parseDouble(etudiants[i+1]));
								juin = 0;
								etudiantsEJB.add(etudiant);
							}
							break;
						case "updateSept":
							for(int i=1; i<etudiants.length; i=i+2){
								matricule = Integer.parseInt(etudiants[i]);
								etudiant = gestionEtudiants.getEtudiantViaMatricule(matricule);
								if(!etudiants[i+1].isEmpty())
									etudiant.setSeptembre(Double.parseDouble(etudiants[i+1]));
								septembre = 0;
								etudiantsEJB.add(etudiant);
							}
							break;
						case "updateGrade":
							for(int i=1; i<etudiants.length; i=i+2){
								matricule = Integer.parseInt(etudiants[i]);
								etudiant = gestionEtudiants.getEtudiantViaMatricule(matricule);
								if(!etudiants[i+1].isEmpty())
									etudiant.setGrade(etudiants[i+1]);
								grade = null;
								etudiantsEJB.add(etudiant);
							}
							break;
						case "nouveaux":
							for(int i=1; i<etudiants.length; i=i+8){
								matricule = Integer.parseInt(etudiants[i]);
								String nom = etudiants[i+1];
								String prenom = etudiants[i+2];
								if(!etudiants[i+3].isEmpty())
									email = etudiants[i+3];
								if(!etudiants[i+4].isEmpty())
									janvier = Double.parseDouble(etudiants[i+4]);
								if(!etudiants[i+5].isEmpty())
									juin = Double.parseDouble(etudiants[i+5]);
								if(!etudiants[i+6].isEmpty())
									septembre = Double.parseDouble(etudiants[i+6]);
								if(!etudiants[i+7].isEmpty())
									grade = etudiants[i+7];
								boolean erasmus = false;
								int annee = (new GregorianCalendar()).get(Calendar.YEAR);
								int numero = 0;
								etudiant = new Etudiant(matricule,nom,prenom,email,annee,erasmus,null,janvier,juin,septembre,grade,numero,null);
								email = null; grade = null; 
								janvier = 0; juin = 0; septembre = 0;
								etudiantsEJB.add(etudiant);
							}
							break;
						}
						
						responseCode = gestionEtudiants.enregistrerEtudiantsEnDB(etudiantsEJB);

						Hashtable<String, Object> json = new Hashtable<String, Object>();
						json.put("success", responseCode);
						response.setContentType("application/json");
						response.setCharacterEncoding("UTF-8");
						response.getWriter().write(
								new GsonBuilder().create().toJson(json));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementPersistDelibe(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String listGarder = request.getParameter("listGarder");
				String listSupprimmer = request.getParameter("listSupprimmer");
				
				if (Util.checkObject(listGarder)
						&& Util.checkObject(listSupprimmer)) {
					boolean responseCode = true;

					if (Util.checkString(listGarder)) {
						String[] matricules = listGarder.split(",");
						
						for (int i = 0; i < matricules.length; i++) {
							int matricule = Integer.parseInt(matricules[i]);
							if(!gestionEtudiants.garderEtudiant(matricule)){
								responseCode = false;
							}
						}
					}

					if (Util.checkString(listSupprimmer)) {
						String[] matricules = listSupprimmer.split(",");
						
						for (int i = 0; i < matricules.length; i++) {
							int matricule = Integer.parseInt(matricules[i]);
							if(!gestionEtudiants.supprimerEtudiant(matricule)){
								responseCode = false;
							}
						}
					}
					
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementGetAllEtudiantsParAnnee(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String annee = request.getParameter("annee");
				if (Util.checkString(annee)) {
					Integer anneeInt = Integer.parseInt(annee);

					List<Etudiant> allEtudiantsDeLAnnee = gestionEtudiants.getEtudiantsByAnnee(anneeInt);
					
					List<EtudiantDTO> etudiantsDTO = EtudiantDTO.convertirEnListeDEtudiantsDTO(allEtudiantsDeLAnnee);
					
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("etudiantsDAnnee", etudiantsDTO);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementGetAllAnnees(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				List<Integer> allAnnees = gestionEtudiants.getToutesLesAnnees();
				
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("allAnnees", allAnnees);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private void traitementUpdateEtudiants(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputEtudiants = request.getParameter("inputEtudiants");
				if (Util.checkObject(inputEtudiants)) {
					boolean responseCode = true;

					// numero matricule nom prenom email annee erasmus janvier
					// juin septembre grade numeroserie;

					if (Util.checkString(inputEtudiants)) {
						String[] etudiants = inputEtudiants.split(",");
						List<EtudiantDTO> etudiantsDTO = new ArrayList<EtudiantDTO>();
						EtudiantDTO etudiantDTO = null;
						String nom = null, prenom = null, email = null, grade = null;
						double janvier = 0, juin = 0, septembre = 0;
						for (int i = 0; i < etudiants.length; i++) {
							switch (i % 7) {
							case 0:
								nom = etudiants[i];
								break;
							case 1:
								prenom = etudiants[i];
								break;
							case 2:
								email = etudiants[i];
								break;
							case 3:
								janvier = Double.parseDouble(etudiants[i]);
								break;
							case 4:
								juin = Double.parseDouble(etudiants[i]);
								break;
							case 5:
								septembre = Double.parseDouble(etudiants[i]);
								break;
							case 6:
								grade = etudiants[i];
								etudiantDTO = new EtudiantDTO();
								etudiantDTO.setNom(nom);
								etudiantDTO.setPrenom(prenom);
								etudiantDTO.setEmail(email);
								etudiantDTO.setJanvier(janvier);
								etudiantDTO.setJuin(juin);
								etudiantDTO.setSeptembre(septembre);
								etudiantDTO.setGrade(grade);
								etudiantsDTO.add(etudiantDTO);
							}
						}

						List<Etudiant> allEtudiants = gestionEtudiants
								.getTousLesEtudiants();
						allEtudiants = EtudiantDTO.mergeToListEtudiant(
								etudiantsDTO, allEtudiants);

						responseCode = gestionEtudiants
								.enregistrerEtudiantsEnDB(allEtudiants);

						Hashtable<String, Object> json = new Hashtable<String, Object>();
						json.put("success", responseCode);
						response.setContentType("application/json");
						response.setCharacterEncoding("UTF-8");
						response.getWriter().write(
								new GsonBuilder().create().toJson(json));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void traitementGetAllEtudiants(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				List<Etudiant> allEtudiants = gestionEtudiants
						.getTousLesEtudiants();

				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("allEtudiants", allEtudiants);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementNumeroterEtudiants(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {

				List<Etudiant> allEtudiants = gestionEtudiants
						.getTousLesEtudiants();
				boolean responseCode = gestionEtudiants
						.numeroterLesEtudiants(allEtudiants);

				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("success", responseCode);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementExporterEtudiants(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String export = gestionEtudiants.getEtudiantsForExportExcel();
				
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("excel", export);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementEnregistrerIntersections(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputMatrice = request.getParameter("inputMatrice");
				if (Util.checkString(inputMatrice)) {
					String[] matriceVals = inputMatrice.split(",");
					int compteurMatrice = 0;

					int nombreDOptions = gestionOptions
							.visualiserToutesLesOptions().size();
					boolean[][] matriceParam = new boolean[nombreDOptions][nombreDOptions];
					for (int i = 0; i < matriceParam.length; i++) {
						for (int j = 0; j < matriceParam.length; j++) {
							matriceParam[i][j] = Boolean
									.parseBoolean(matriceVals[compteurMatrice]);
							compteurMatrice++;
						}
					}

					boolean responseCode = gestionOptions
							.definirIntersectionsInterditesDOptions(matriceParam);

					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementGetIntersectionsImpossibles(
			HttpServletRequest request, HttpServletResponse response,
			Integer level) {
		if (level == 0) {
			try {
				List<Option> allOptions = gestionOptions
						.visualiserToutesLesOptions();
				boolean[][] matriceDIntersections = gestionOptions
						.getIntersectionsInterditesDOptions();
				List<Boolean> matriceFormatArray = new ArrayList<Boolean>();
				
				for(int i=0; i< matriceDIntersections.length; i++){
					for (int j = 0; j < matriceDIntersections.length; j++) {
						matriceFormatArray.add(matriceDIntersections[i][j]);
					}
				}
				
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("allOptions", allOptions);
				json.put("matriceFormatArray", matriceFormatArray);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementGetAllEtudiantMalheureux(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				Object[][] etudMalheureux = gestionEtudiants
						.getAllEtudiantsMalheureux();
				for (int i = 0; i < etudMalheureux.length; i++) {
					etudMalheureux[i][0] = new EtudiantDTO(
							(Etudiant) etudMalheureux[i][0]);
				}
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("etudMalheureux", etudMalheureux);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementGetAllOptions(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				List<Option> options = gestionOptions
						.visualiserToutesLesOptions();
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("options", options);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementGetAllEtudiantPourLOption(
			HttpServletRequest request, HttpServletResponse response,
			Integer level) {
		if (level == 0) {
			try {
				String inputOption = request.getParameter("inputOption");
				if (Util.checkString(inputOption)) {
					int idOption = Integer.parseInt(inputOption);
					List<Etudiant> allEtudiantsPourLOption = gestionEtudiants
							.getAllEtudiantsAyantGagnantLOption(idOption);
					List<EtudiantDTO> etudPourLOption = EtudiantDTO
							.convertirEnListeDEtudiantsDTO(allEtudiantsPourLOption);
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("etudPourLOption", etudPourLOption);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void traitementGetAllEtudiantAvecOptionsGagnantes(
			HttpServletRequest request, HttpServletResponse response,
			Integer level) {
		if (level == 0) {
			try {
				Object[][] etudAvecOptions = gestionEtudiants
						.getAllEtudiantsAvecChoixGagnants();
				for (int i = 0; i < etudAvecOptions.length; i++) {
					etudAvecOptions[i][0] = new EtudiantDTO(
							(Etudiant) etudAvecOptions[i][0]);
				}
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("etudAvecOptions", etudAvecOptions);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementUpdateOptionsOptionnels(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputOptions = request.getParameter("inputOptions");
				String inputOptionnels = request
						.getParameter("inputOptionnels");
				if (Util.checkObject(inputOptions)
						&& Util.checkObject(inputOptionnels)) {
					boolean responseCode = true;

					if (Util.checkString(inputOptions)) {
						String[] options = inputOptions.split(",");
						List<Option> optionsToEJB = new ArrayList<Option>();
						Option option = null;
						int id = 0, annee_debut = 0, annee_fin;
						double ects = 0;
						String code = null, intitule = null;
						for (int i = 0; i < options.length; i++) {
							switch (i % 6) {
							case 0:
								id = Integer.parseInt(options[i]);
								break;
							case 1:
								code = options[i];
								break;
							case 2:
								intitule = options[i];
								break;
							case 3:
								ects = Double.parseDouble(options[i]);
								break;
							case 4:
								annee_debut = Integer.parseInt(options[i]);
								break;
							case 5:
								annee_fin = Integer.parseInt(options[i]);
								option = new Option(code, intitule, ects,
										annee_debut, annee_fin);
								option.setId(id);
								optionsToEJB.add(option);
								break;
							}
						}
						if (!gestionOptions.modifierOption(optionsToEJB)) {
							responseCode = false;
						}
					}

					if (Util.checkString(inputOptionnels)) {
						String[] optionnels = inputOptionnels.split(",");
						List<Optionnel> optionnelsToEJB = new ArrayList<Optionnel>();
						Optionnel optionnel = null;
						int id = 0, annee_debut = 0, annee_fin;
						double ects = 0;
						String code = null, intitule = null;
						for (int i = 0; i < optionnels.length; i++) {
							switch (i % 6) {
							case 0:
								id = Integer.parseInt(optionnels[i]);
								break;
							case 1:
								code = optionnels[i];
								break;
							case 2:
								intitule = optionnels[i];
								break;
							case 3:
								ects = Double.parseDouble(optionnels[i]);
								break;
							case 4:
								annee_debut = Integer.parseInt(optionnels[i]);
								break;
							case 5:
								annee_fin = Integer.parseInt(optionnels[i]);
								optionnel = new Optionnel(code, intitule, ects,
										annee_debut, annee_fin);
								optionnel.setId(id);
								optionnelsToEJB.add(optionnel);
								break;
							}
						}
						if (!gestionOptionnels
								.modifierOptionnel(optionnelsToEJB)) {
							responseCode = false;
						}
					}
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementPersistNewOptionnel(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputCodeNew = request.getParameter("inputCodeNew");
				String inputIntituleNew = request
						.getParameter("inputIntituleNew");
				String inputEctsNew = request.getParameter("inputEctsNew");
				String inputAnneeDebutNew = request
						.getParameter("inputAnneeDebutNew");
				String inputAnneeFinNew = request
						.getParameter("inputAnneeFinNew");
				if (Util.checkString(inputCodeNew)
						&& Util.checkString(inputIntituleNew)
						&& Util.checkString(inputEctsNew)
						&& Util.checkString(inputAnneeDebutNew)
						&& Util.checkString(inputAnneeFinNew)) {
					Optionnel opt = new Optionnel();
					opt.setCode(inputCodeNew);
					opt.setIntitule(inputIntituleNew);
					opt.setEcts(Double.parseDouble(inputEctsNew));
					opt.setAnnee_debut(Integer.parseInt(inputAnneeDebutNew));
					opt.setAnnee_fin(Integer.parseInt(inputAnneeFinNew));
					boolean responseCode = gestionOptionnels
							.enregistrerOptionnel(opt);
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementPersistNewOption(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputCodeNew = request.getParameter("inputCodeNew");
				String inputIntituleNew = request
						.getParameter("inputIntituleNew");
				String inputEctsNew = request.getParameter("inputEctsNew");
				String inputAnneeDebutNew = request
						.getParameter("inputAnneeDebutNew");
				String inputAnneeFinNew = request
						.getParameter("inputAnneeFinNew");
				if (Util.checkString(inputCodeNew)
						&& Util.checkString(inputIntituleNew)
						&& Util.checkString(inputEctsNew)
						&& Util.checkString(inputAnneeDebutNew)
						&& Util.checkString(inputAnneeFinNew)) {
					Option opt = new Option();
					opt.setCode(inputCodeNew);
					opt.setIntitule(inputIntituleNew);
					opt.setEcts(Double.parseDouble(inputEctsNew));
					opt.setAnnee_debut(Integer.parseInt(inputAnneeDebutNew));
					opt.setAnnee_fin(Integer.parseInt(inputAnneeFinNew));
					boolean responseCode = gestionOptions
							.enregistrerOption(opt);
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementDeleteOptionsOptionnels(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputOptions = request.getParameter("inputOptions");
				String inputOptionnels = request
						.getParameter("inputOptionnels");
				if (Util.checkObject(inputOptions)
						&& Util.checkObject(inputOptionnels)) {
					String[] options = inputOptions.split(",");
					String[] optionnels = inputOptionnels.split(",");
					boolean responseCode = true;
					if (Util.checkString(inputOptions)) {
						for (int i = 0; i < options.length; i++) {
							Integer idOption = Integer.parseInt(options[i]);
							if (!gestionOptions.supprimerOption(idOption)) {
								responseCode = false;
							}
						}
					}

					if (Util.checkString(inputOptionnels)) {
						for (int i = 0; i < optionnels.length; i++) {
							Integer idOptionnel = Integer
									.parseInt(optionnels[i]);
							if (!gestionOptionnels
									.supprimerOptionnel(idOptionnel)) {
								responseCode = false;
							}
						}
					}
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void traitementGetOptionsAndOptionnels(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				List<Option> options = gestionOptions
						.visualiserToutesLesOptions();
				List<Optionnel> optionnels = gestionOptionnels
						.visualiserTousLesCoursOptionnels();
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("options", options);
				json.put("optionnels", optionnels);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementSendMailToAll(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				boolean responseCode = gestionEtudiants
						.envoyerMailATousLesEtudiants("Chers étudiants, veuillez encoder vos choix.");
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("success", responseCode);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementPersistBorneOpt(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputBorneOpt = request.getParameter("inputBorneOpt");
				if (Util.checkString(inputBorneOpt)) {
					Integer borne = Integer.parseInt(inputBorneOpt);
					boolean responseCode = gestionInscription
							.setBorneCoursOptionnels(borne);
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementPersistDates(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String inputDateDebut = request.getParameter("inputDateDebut");
				String inputDateFin = request.getParameter("inputDateFin");
				if (Util.checkString(inputDateDebut)
						&& Util.checkString(inputDateFin)) {
					boolean responseCode = gestionChoix.setDateDebutEtFin(
							inputDateDebut, inputDateFin);
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementGetDatesAndBorneOpt(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level == 0) {
			try {
				String dateDebut = gestionChoix.getDateDebut();
				String dateFin = gestionChoix.getDateFin();
				Integer optMax = gestionInscription.getBorneCoursOptionnels();
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("dateDebut", dateDebut);
				json.put("dateFin", dateFin);
				json.put("borneOpt", optMax);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void traitementPersistChoix(HttpServletRequest request,
			HttpServletResponse response, Integer level) {
		if (level > 0) {
			try {
				String inputChoix = request.getParameter("inputChoix");
				String inputInscriptions = request
						.getParameter("inputInscriptions");
				String estErasmus = request.getParameter("estErasmus");
				String message = "";
				if (Util.checkString(inputChoix)
						&& Util.checkString(inputInscriptions)
						&& Util.checkString(estErasmus)) {
					Etudiant etudiantCourant = gestionEtudiants
							.getEtudiantViaMatricule(level);
					boolean responseCode = false;
					boolean isDateFinAtteinte = gestionChoix
							.isDateDeFinDesChoixAtteinte();
					if (!isDateFinAtteinte) {
						if (Boolean.parseBoolean(estErasmus)) {
							etudiantCourant.setErasmus(true);
							responseCode = gestionEtudiants
									.erasmus(etudiantCourant);
						} else {
							etudiantCourant.setErasmus(false);
							responseCode = gestionEtudiants
									.erasmus(etudiantCourant);
							String[] choix = inputChoix.split(",");
							String[] inscriptions = inputInscriptions
									.split(",");
							Integer coursOptionnelMax = gestionInscription
									.getBorneCoursOptionnels();
							int cpt = 0;
							for (int i = 0; i < inscriptions.length; i++) {
								if (inscriptions[i].equals("true")) {
									cpt++;
								}
							}
							if (cpt > coursOptionnelMax) {
								message = "Le nombre maximum de cours optionnel a été atteint !";
								responseCode = false;
							} else {
								List<Integer> ordrePreferenceChoix = new ArrayList<Integer>();
								for (int i = 0; i < choix.length; i++) {
									Integer id = Integer.parseInt(choix[i]);
									ordrePreferenceChoix.add(id);
								}
								List<Optionnel> optionnels = gestionOptionnels
										.visualiserTousLesCoursOptionnels();
								Map<Integer, Boolean> mapPreferenceInscriptions = new HashMap<Integer, Boolean>();
								for (int i = 0; i < optionnels.size(); i++) {
									mapPreferenceInscriptions.put(optionnels
											.get(i).getId(), Boolean
											.parseBoolean(inscriptions[i]));
								}
								responseCode = gestionChoix
										.enregistrerSesChoixDOptions(
												etudiantCourant,
												ordrePreferenceChoix);
								responseCode = gestionInscription
										.enregistrerSesInscriptions(
												etudiantCourant,
												mapPreferenceInscriptions);

							}

						}
					}
					if (responseCode == false && message.trim().equals("")) {
						message = "Erreur lors de votre encodage.";
					}
					Hashtable<String, Object> json = new Hashtable<String, Object>();
					json.put("success", responseCode);
					json.put("message", message);
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							new GsonBuilder().create().toJson(json));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementGetChoix(HttpServletRequest request,
			HttpServletResponse response, Integer matricule) {
		try {
			Etudiant etudiantCourant = gestionEtudiants
					.getEtudiantViaMatricule(matricule);
			boolean isDateFinAtteinte = gestionChoix
					.isDateDeFinDesChoixAtteinte();
			List<Option> options = gestionChoix
					.visualiserTousSesChoix(etudiantCourant);
			List<Optionnel> mesOptionnels = gestionInscription
					.visualiserTousSesInscriptions(etudiantCourant);
			List<Optionnel> tousLesOptionnels = gestionOptionnels
					.visualiserTousLesCoursOptionnels();
			boolean isErasmus = true;

			List<Boolean> inscriptions = new ArrayList<Boolean>();
			for (int i = 0; i < tousLesOptionnels.size(); i++) {
				boolean succes = false;
				Integer id = tousLesOptionnels.get(i).getId();
				for (int j = 0; j < mesOptionnels.size(); j++) {
					if (mesOptionnels.get(j).getId() == id) {
						inscriptions.add(true);
						succes = true;
						break;
					}
				}
				if (!succes) {
					inscriptions.add(false);
				}
			}
			if (options.size() != 0) {
				isErasmus = etudiantCourant.isErasmus();
			} else {
				options = gestionOptions.visualiserToutesLesOptions();
			}

			Hashtable<String, Object> json = new Hashtable<String, Object>();
			json.put("dateFinAtteinte", isDateFinAtteinte);
			json.put("estErasmus", isErasmus);
			json.put("options", options);
			json.put("optionnels", tousLesOptionnels);
			json.put("mesOptionnels", inscriptions);
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(new GsonBuilder().create().toJson(json));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	private void traitementLogin(HttpServletRequest request,
			HttpServletResponse response) {
		String matricule = request.getParameter("inputMatricule");
		String mdp = request.getParameter("inputPassword");
		if (Util.checkString(matricule) && Util.checkString(mdp)) {

			try {
				int responseCode = gestionEtudiants.authentifierVisiteur(
						matricule, mdp);
				boolean isConnecte = false;
				String message = "";

				if (responseCode == -2) {
					message = "La date de début d'encodage des choix n'a pas encore été atteinte.";
				} else if (responseCode == -1) {
					message = "Vos identifiants sont incorrects";
				} else if (responseCode == 0) {
					message = "prof";
					isConnecte = true;
				} else {
					message = "etudiant";
					isConnecte = true;
				}

				if (isConnecte) {
					HttpSession session = request.getSession();
					try {
						synchronized (session) {
								session.setAttribute("matricule", matricule);
								session.setAttribute("level", responseCode);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("message", message);
				json.put("success", isConnecte);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void traitementgetPasswordByMail(HttpServletRequest request,
			HttpServletResponse response) {
		String matricule = request.getParameter("inputMatriculeOublie");
		if (Util.checkString(matricule)) {
			boolean responseCode = false;
			try {
				responseCode = gestionEtudiants.envoyerMailAvecMDPA(matricule);
				Hashtable<String, Object> json = new Hashtable<String, Object>();
				json.put("success", responseCode);
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(
						new GsonBuilder().create().toJson(json));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}